<?php

namespace app\admin\controller;

use app\admin\model\Fake as ModelFake;
use app\admin\model\Goods;
use think\exception\ValidateException;
use think\facade\Db;

class Fake extends Base
{
    public function index()
    {
        $goodList = Goods::where('type', 1)->select();
        return view('index', ['goodList' => $goodList]);
    }
    public function add()
    {
        $goodList = Goods::where('status', 1)->select();
        return view('add', ['goodList' => $goodList]);
    }
    public function doAdd()
    {
        $param = input();
        ModelFake::add($param);
        return success();
    }
    // 提取卡密 -> 改变卡密状态为 2（已提取）
    public function getFake()
    {
        $param = input();
        $res = ModelFake::getFake($param);
        dump($res);die;
        return success($res);
    }
    public function list()
    {
        $param = input();
        $fake = @$param['fake'];
        $limit = $param['limit'] ?? 10;
        if (empty($fake)) {
            $list = ModelFake::order('status asc,id desc')->paginate($limit);
        } else {
            $list = ModelFake::where('fake', 'like', '%' . $fake . '%')->order('status asc,id desc')->paginate($limit);
        }
        foreach($list as $k => $v)
        {
            if($v['good_id'])
            {
                $list[$k]['good_name'] = Db::name('goods')->where('id' , $v['good_id'])->value('good_name');
            }
        }
        return success($list, '操作成功', 0);
    }
    public function update()
    {
        if (request()->isPost()) {
            $param = input();
            $res = ModelFake::update($param);
            if ($res) return success();
            else return error();
        }
    }
    public function del($id)
    {
        $id = input('id');
        $idArr = explode(',',$id);
        $res = ModelFake::whereIn('id',$idArr)->delete();
        if ($res) return success();
        else return error();
    }
    public function import()
    {
        $goodList = Goods::where(['status' => 1 , 'type' => 1])->select();
        return view('import', ['goodList' => $goodList]);
    }
    // 导入卡密 （卡密商品）
    public function doImport()
    {
        $param = input();
        $fakeContent = $param['fakeContent'];
        $good_id = $param['good_id'];
        $fakeArr = explode("\n", $fakeContent);
        for ($i = 0; $i < count($fakeArr); $i++) {
            if (!empty($fakeArr[$i])) {
                $hasFake =  ModelFake::where('fake', $fakeArr[$i])->findOrEmpty()->isEmpty();
                if ($hasFake) {
                    ModelFake::create(['fake' => $fakeArr[$i], 'good_id' => $good_id,'type' => 2]);
                }
            }
        }
        return success();
    }
}
